package org.example.file;

import com.alibaba.fastjson2.JSONObject;
import io.jsonwebtoken.lang.Assert;
import org.example.core.enums.ApiResult;
import org.example.core.exception.ErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

/**
 * 文件上传下载控制层
 */
@RestController
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Value("${file.path}")
    private String filePath;

    @RequestMapping("/upload")
    public ApiResult upload(MultipartFile file, HttpServletRequest request) {
        Assert.hasLength(filePath, "文件路径参数不能为空！");
        JSONObject fileJsonObject = new JSONObject();
        String fileName = System.currentTimeMillis() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        fileJsonObject.put("fileName",fileName);
        fileJsonObject.put("originalFileName",file.getOriginalFilename());
        logger.info("{}上传文件-------名称------>{}", getRealIP(request), fileName);
        try {
            InputStream inputStream = file.getInputStream();
            File newFile = new File(filePath + fileName);
            FileOutputStream outputStream = new FileOutputStream(newFile);
            FileCopyUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            throw new ErrorException(e);
        }
        return ApiResult.success(fileJsonObject);
    }

    public static String getRealIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null) {
            ip = ip.contains(",") ? ip.split(",")[0] : ip;
        } else {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        }
        return ip;
    }

}
